#include "ACifDataLoader.h"

ACifDataLoader::ACifDataLoader()
{
	cifFile = NULL;
	cifData = NULL;
	errorCode = 0;
}

ACifDataLoader::~ACifDataLoader()
{
	if (cifFile != NULL)
	{
		fclose(cifFile);
	}
}

CifData *ACifDataLoader::Load(const char *fileName)
{
	if (cifFile != NULL)
	{
		fclose(cifFile);
		cifFile = NULL;
	}

	cifFile = fopen(fileName, "r");
	if (cifFile == NULL)
	{
		perror("Unable to open input file.");
		return NULL;
	}

	cifData = new CifData();

	Parse();

	if (errorCode != CIF_ERROR_CODE_OK)
	{
		perror("Unable to parse input file.");
		if (cifData != NULL)
		{
			delete(cifData);
			cifData = NULL;
		}
	}

	if (cifFile != NULL)
	{
		fclose(cifFile);
		cifFile = NULL;
	}

	return cifData;
}

void ACifDataLoader::PrintErrorMessage(char *msg)
{
	switch (errorCode)
	{
	case CIF_ERROR_CODE_OK:
		perror("No errors.");
		break;
	case CIF_ERROR_CODE_FILE_OPEN_FAILED:
		break;
	case CIF_ERROR_CODE_FILE_SYNTAX_ERROR:
		perror("ERROR! Syntax error.");
		break;
	case CIF_ERROR_CODE_INTERNAL_ERROR:
		perror("ERROR! Internal error.");
		break;
	default:
		perror("ERROR! Unknown error code.");
		break;
	}

	perror(msg);
}

int ACifDataLoader::IsEof()
{
	return feof(cifFile);
}